package com.sdlh.demo.springboot.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
    public static final String EXECUTOR_NAME = "async_executor";

    @Override
    public Executor getAsyncExecutor() {
        log.info("--获取spring异步线程池--");
        return threadPool();
    }

    @Bean(EXECUTOR_NAME)
    public ThreadPoolTaskExecutor threadPool() {
        log.info("--创建spring异步线程池--");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数10
        executor.setCorePoolSize(10);
        //最大线程数30
        executor.setMaxPoolSize(30);
        //缓冲队列100
        executor.setQueueCapacity(100);
        //允许线程的空闲时间60秒
        executor.setKeepAliveSeconds(60);
        //线程池名称前缀
        executor.setThreadNamePrefix(EXECUTOR_NAME + "-");
        //当到达最大线程数是如何处理新任务
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }
}
